package com.dz51.core.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

/**
 * @Title: SessionFactorySubUtils.java
 * @Package com.dz51.utils
 * @Description: 实现SessionFactoryUtils --------------- session过度本地线程
 * @author Zhaoqt
 * @date 2014-5-2 下午6:05:51
 * @version V1.0
 */
public class SessionFactorySubUtils extends SessionFactoryUtils {

	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

	private static SessionFactory sessionFactory;

	private SessionFactorySubUtils() {

	}

	public static void initSessionFactory(SessionFactory sessionFactory) {
		SessionFactorySubUtils.sessionFactory = sessionFactory;
	}

	/**
	 * @Title: getSession
	 * @Description: 获取session ------------ threadLocal中获取若不存在
	 *               openSession并放入threadLocal中
	 * @param @return
	 * @param @throws HibernateException
	 * @return Session
	 * @throws
	 */
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			session = (sessionFactory != null) ? sessionFactory.openSession() : null;
			threadLocal.set(session);
		}

		return session;
	}

	/**
	 * @Title: closeSession
	 * @Description: 关闭 threadLocal线程session
	 * @param @throws HibernateException
	 * @return void
	 * @throws
	 */
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

		if (session != null) {
			session.close();
		}
	}

	/**
	 * @Title: getNewSession
	 * @Description: 封装父类getNewSession()
	 * @param @return
	 * @param @throws HibernateException
	 * @return Session
	 * @throws
	 */
	public static Session getNewSession() throws HibernateException {
		Session session = (sessionFactory != null) ? getNewSession(sessionFactory) : null;
		return session;
	}
}
